//
//  MyFootprintViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/4.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "MyFootprintViewController.h"

#import "FPCommodityDetailVC.h"
#import "ShopAdornViewController.h"
#import "CaseDetailsViewController.h"
//cell
#import "ServeCollectionCell.h"
#import "ShopAttentionCell.h"
#import "CaseTableViewCell.h"

@interface MyFootprintViewController ()<UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *moveLine;
@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, assign) NSInteger state;

@property (nonatomic, strong) NSMutableArray  *dataArray;
@property (nonatomic, strong) NSMutableArray  *pagesArray;
@property (nonatomic, strong) NSMutableArray  *currentPageArray;

@end

@implementation MyFootprintViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setShadowImage:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"我的足迹";
    self.state = 0;
    self.dataArray = [NSMutableArray array];
    self.pagesArray = [NSMutableArray array];
    self.currentPageArray = [NSMutableArray array];
    for (int i = 0; i < 3; i++) {
        NSMutableArray *array = [NSMutableArray array];
        [self.dataArray addObject:array];
        [self.pagesArray addObject:@"1"];
        [self.currentPageArray addObject:@"1"];
    }
    
    [self setTopBar];
    [self setUI];
}

- (void)setTopBar {
    UIView *topBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(30))];
    topBar.backgroundColor = RGB_COLOR(235, 67, 90);
    [self.view addSubview:topBar];
    
    NSArray *nameArr = @[@"看过的服务",@"看过的设计师",@"看过的案例"];
    for (int i = 0; i < nameArr.count; i++) {
        UIButton *typeBtn = [[UIButton alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH / 3, 0, SCREEN_WIDTH / 3, ScreenX375(30))];
        [typeBtn setTitle:nameArr[i] forState:UIControlStateNormal];
        [typeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [typeBtn setTitleColor:RGBACOLOR(255, 255, 255, 0.6) forState:UIControlStateNormal];
        typeBtn.titleLabel.font = Kfont(16);
        typeBtn.tag = 100 + i;
        if (i == 0) {
            typeBtn.selected = YES;
            _selectBtn = typeBtn;
        }
        [typeBtn addTarget:self action:@selector(typeClick:) forControlEvents:UIControlEventTouchUpInside];
        [topBar addSubview:typeBtn];
    }
    
    self.moveLine = [[UIView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH / 3 - ScreenX375(30)) / 2, ScreenX375(30) - 2, ScreenX375(30), 2)];
    self.moveLine.backgroundColor = [UIColor whiteColor];
    [topBar addSubview:self.moveLine];
}

- (void)typeClick:(UIButton *)button {
    _selectBtn.selected = NO;
    button.selected = YES;
    _selectBtn = button;
    _state = button.tag - 100;
    if (button.tag == 100 + _state && [_dataArray[_state] count] == 0) {
        BaseTableView *tableView = [self.view viewWithTag:200 + _state];
        [tableView.mj_header beginRefreshing];
    }
    [UIView animateWithDuration:0.3 animations:^{
        self.moveLine.frame = CGRectMake((SCREEN_WIDTH / 3 - ScreenX375(30)) / 2 + (button.tag - 100) * SCREEN_WIDTH / 3, ScreenX375(30) - 2, ScreenX375(30), 2);
    }];
    [_scrollView setContentOffset:CGPointMake((button.tag - 100) * SCREEN_WIDTH, 0) animated:YES];
}

- (void)setUI {
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, ScreenX375(30), SCREEN_WIDTH, SCREEN_HEIGHT - ScreenX375(30))];
    _scrollView.showsVerticalScrollIndicator = false;
    _scrollView.showsHorizontalScrollIndicator = false;
    _scrollView.pagingEnabled = true;
    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 3, 0);
    [self.view addSubview:_scrollView];
    
    for (int i = 0; i < 3; i++) {
        BaseTableView *tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(30))];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor whiteColor];
        tableView.tag = 200 + i;
        if (i == 0) {
            tableView.rowHeight = ScreenX375(101);
        }else if (i == 1) {
            tableView.rowHeight = ScreenX375(111);
        }else {
            tableView.rowHeight = ScreenX375(108);
        }
        
        [_scrollView addSubview:tableView];
        
        __weak __typeof(self)weakSelf = self;
        tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf.currentPageArray replaceObjectAtIndex:weakSelf.state withObject:@"1"];
            
            NSString *url = @"";
            NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken],@"page":@"1",@"longitude":kNSUDefaultReadKey(@"longitude"),@"latitude":kNSUDefaultReadKey(@"latitude")};
            switch (weakSelf.state) {
                case 0:
                    url = [NSString stringWithFormat:@"%@app/service_browse_record",REQUESTHEADER];
                    break;
                case 1:
                    url = [NSString stringWithFormat:@"%@app/shop_browse_record",REQUESTHEADER];
                    break;
                case 2:
                    dict = @{@"token":[FPLoginAndRegisterTools getToken],@"page":@"1"};
                    url = [NSString stringWithFormat:@"%@app/case_browse_record",REQUESTHEADER];
                    break;
                default:
                    break;
            }
            
            [HttpManager postHttpRequestByGet:url andParameter:dict success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
                if ([status isEqualToString:@"1"]) {
                    [tableView.mj_header endRefreshing];
                    NSError *error;
                    [weakSelf.dataArray[weakSelf.state] removeAllObjects];
                    [weakSelf.pagesArray replaceObjectAtIndex:weakSelf.state withObject:[NSString stringWithFormat:@"%@",successResponse[@"data"][@"last_page"]]];
                    if (weakSelf.state == 0) {
                        for (NSDictionary *dic in successResponse[@"data"][@"data"]) {
                            ServeGoodsDataModel *model = [[ServeGoodsDataModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.dataArray[weakSelf.state] addObject:model];
                        }
                    }else if (weakSelf.state == 1) {
                        for (NSDictionary *dic in successResponse[@"data"][@"data"]) {
                            DesignListDataModel *model = [[DesignListDataModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.dataArray[weakSelf.state] addObject:model];
                        }
                    }else if (weakSelf.state == 2) {
                        for (NSDictionary *dic in successResponse[@"data"][@"data"]) {
                            CreateAreaDataModel *model = [[CreateAreaDataModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.dataArray[weakSelf.state] addObject:model];
                        }
                    }
                    if ([weakSelf.pagesArray[weakSelf.state] isEqualToString:weakSelf.currentPageArray[weakSelf.state]]) {
                        tableView.mj_footer.hidden = YES;
                    }
                    [tableView reloadData];
                    
                }else{
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
                }
            } andFailure:^(id failureResponse) {
                [tableView.mj_header endRefreshing];
                [HttpManager showFail];
            }];
        }];
        
        tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            NSInteger page = [weakSelf.currentPageArray[weakSelf.state] integerValue];
            [weakSelf.currentPageArray replaceObjectAtIndex:weakSelf.state withObject:[NSString stringWithFormat:@"%ld",page + 1]];
            
            NSString *url = @"";
            NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken],@"page":weakSelf.currentPageArray[weakSelf.state],@"longitude":kNSUDefaultReadKey(@"longitude"),@"latitude":kNSUDefaultReadKey(@"latitude")};
            switch (weakSelf.state) {
                case 0:
                    url = [NSString stringWithFormat:@"%@app/service_browse_record",REQUESTHEADER];
                    break;
                case 1:
                    url = [NSString stringWithFormat:@"%@app/shop_browse_record",REQUESTHEADER];
                    break;
                case 2:
                    dict = @{@"token":[FPLoginAndRegisterTools getToken],@"page":weakSelf.currentPageArray[weakSelf.state]};
                    url = [NSString stringWithFormat:@"%@app/service_browse_record",REQUESTHEADER];
                    break;
                default:
                    break;
            }
            
            [HttpManager postHttpRequestByGet:url andParameter:dict success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
                if ([status isEqualToString:@"1"]) {
                    [tableView.mj_footer endRefreshing];
                    NSError *error;
                    [weakSelf.pagesArray replaceObjectAtIndex:weakSelf.state withObject:[NSString stringWithFormat:@"%@",successResponse[@"data"][@"last_page"]]];
                    if (weakSelf.state == 0) {
                        for (NSDictionary *dic in successResponse[@"data"][@"data"]) {
                            ServeGoodsDataModel *model = [[ServeGoodsDataModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.dataArray[weakSelf.state] addObject:model];
                        }
                    }else if (weakSelf.state == 1) {
                        for (NSDictionary *dic in successResponse[@"data"][@"data"]) {
                            DesignListDataModel *model = [[DesignListDataModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.dataArray[weakSelf.state] addObject:model];
                        }
                    }else if (weakSelf.state == 2) {
                        for (NSDictionary *dic in successResponse[@"data"][@"data"]) {
                            CreateAreaDataModel *model = [[CreateAreaDataModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.dataArray[weakSelf.state] addObject:model];
                        }
                    }
                    if ([weakSelf.pagesArray[weakSelf.state] isEqualToString:weakSelf.currentPageArray[weakSelf.state]]) {
                        tableView.mj_footer.hidden = YES;
                    }
                    [tableView reloadData];
                    
                }else{
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
                }
            } andFailure:^(id failureResponse) {
                [tableView.mj_footer endRefreshing];
                [HttpManager showFail];
            }];
        }];
        
        if (i == 0) {
            [tableView.mj_header beginRefreshing];
        }
    }
}

#pragma mark - UITableViewDelegate,DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_dataArray[tableView.tag - 200] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 200) {
        ServeCollectionCell *cell = [ServeCollectionCell cellWithTableView:tableView andIndexPath:indexPath];
        cell.serveGoodsDataModel = _dataArray[0][indexPath.row];
        return cell;
    }else if (tableView.tag == 201) {
        ShopAttentionCell *cell = [ShopAttentionCell cellWithTableView:tableView andIndexPath:indexPath];
        cell.designListDataModel = _dataArray[1][indexPath.row];
        return cell;
    }else {
        CaseTableViewCell *cell = [CaseTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
        cell.createAreaDataModel = _dataArray[2][indexPath.row];
        return cell;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
        
        UIButton *button = [self.view viewWithTag:index + 100];
        _selectBtn.selected = NO;
        button.selected = YES;
        _selectBtn = button;
        [UIView animateWithDuration:0.3 animations:^{
            self.moveLine.frame = CGRectMake((SCREEN_WIDTH / 3 - ScreenX375(30)) / 2 + (button.tag - 100) * SCREEN_WIDTH / 3, ScreenX375(30) - 2, ScreenX375(30), 2);
        }];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
        
        UIButton *button = [self.view viewWithTag:index + 100];
        _selectBtn.selected = NO;
        button.selected = YES;
        _selectBtn = button;
        _state = button.tag - 100;
        if (button.tag == 100 + _state && [_dataArray[_state] count] == 0) {
            BaseTableView *tableView = [self.view viewWithTag:200 + _state];
            [tableView.mj_header beginRefreshing];
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 201) {
        DesignListDataModel *model = _dataArray[1][indexPath.row];
        ShopAdornViewController *vc = [[ShopAdornViewController alloc] init];
        vc.isMine = NO;
        vc.shop_id = model.Id;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (tableView.tag == 202) {
        CreateAreaDataModel *model = _dataArray[2][indexPath.row];
        CaseDetailsViewController *vc = [[CaseDetailsViewController alloc] init];
        vc.design_id = [model.Id integerValue];
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        ServeGoodsDataModel *model = _dataArray[0][indexPath.row];
        FPCommodityDetailVC *vc = [[FPCommodityDetailVC alloc] init];
        vc.design_id = [model.Id integerValue];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
